import { isUndefined } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createStoreApiMWRouter } from "../../middleware/store-api/storeOwnerChecker";
import pageMW from "../../middleware/pager";
const router = createStoreApiMWRouter();
import {
  listOrderItemsForStore,
  getOrderBySerialNumber,
} from "../../service/orderService";
import { isSearchTerm } from "../../bg-enums/searchTerm";
import OrderStatus, { isOrderStatus } from "../../bg-enums/orderStatus";

// 获取品牌售出订单
router.get("/sto/:storeId/orders", pageMW, async (ctx: AppCTX, next) => {
  const { storeId } = ctx.params;
  const { searchTerm, searchValue, isAll, orderStatus } = ctx.query;
  const { userId, limit, offset, ts } = ctx; // 这个是操作人
  let arrOrderStatus: OrderStatus[] = [];
  if (!isUndefined(orderStatus)) {
    for (let ps of orderStatus.split(",")) {
      if (!isOrderStatus(ps)) {
        ctx.throw(400, "orderStatus invalid");
      }
      arrOrderStatus.push(ps);
    }
  }
  if (!isUndefined(searchTerm) && !isSearchTerm(searchTerm)) {
    ctx.throw(400, "invalid searchTerm");
  }

  const { total, items } = await listOrderItemsForStore(
    {
      storeId,
      isAll: isAll === "true",
      orderStatuses: arrOrderStatus,
      searchTerm,
      searchValue,
    },
    { limit, offset, ts }
  );
  ctx.body = {
    total,
    rows: items,
  };
});

// 获取门店订单详情(门店管理视角)
router.get(
  "/sto/:storeId/order/:orderSerialNumber",
  async (ctx: AppCTX, next) => {
    const { storeId, orderSerialNumber } = ctx.params;
    const { userId } = ctx;

    const order = await getOrderBySerialNumber(orderSerialNumber);
    if (isUndefined(order)) {
      ctx.throw("invalid orderSerialNumber");
    }
    // 代言人自己发布的活动
    if (order.storeId !== storeId) {
      ctx.throw(403, "no belong current store");
    }

    ctx.body = order;
  }
);

export default router;